package com.kgc.web.servlet; /**
 * <h3>项目名称:demo03050</h3>
 * <p>本API描述:${description}</p>
 * <p>@author : AliyZhang</p>
 * <p>@date : 2021-03-08 12:36</p>
 **/

import com.kgc.entity.News;
import com.kgc.service.NewsService;
import com.kgc.service.impl.NewsServiceImpl;
import com.kgc.util.PageSupport;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

@WebServlet(name = "NewsServlet",
        value = "/news.do")
public class NewsServlet extends HttpServlet {
    //创建service对象，供调用
    private NewsService newsService = new NewsServiceImpl();

    @Override
    protected void service(HttpServletRequest request,
                           HttpServletResponse response) throws ServletException, IOException {
        //处理乱码
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=utf-8");
        /*
        1.新闻列表分页展示；   2.新闻增加。3.根据id获取查询新闻信息
        key=list;  key=add ；key=showOne  */
        //获取用户访问的关键字
        String key = request.getParameter("key");
        switch (key) {
            case "list":
                list(request, response);
                break;
            case "add":
                add(request, response);
                break;
            case "showOne":
                showOne(request, response);
                break;
        }
    }

    private void add(HttpServletRequest request, HttpServletResponse response) {
    /*
    处理文件上传
    判断请求是否包含文件上传信息
     */
        try {
            boolean isMultipart = ServletFileUpload.isMultipartContent(request);
            News news = new News();
            if (isMultipart) {
                //创建文件上传的核心组件
                ServletFileUpload upload = new ServletFileUpload(new DiskFileItemFactory());
        /*
        文件上传以后，存到哪里？static/upload/
         */
                //String saveDirPath = request.getServletContext().getRealPath("static/upload");
                //判断上述目录是否存在，如果不存在就创建
                File saveDirFile = new File(request.getServletContext().getRealPath("static/upload"));
                if (!saveDirFile.exists()) {
                    saveDirFile.mkdirs();
                }
        /*解析请求里的参数为List集合
        去接收用户从前端传来的参数
         */

                List<FileItem> items = upload.parseRequest(request);
                Iterator<FileItem> iterator = items.iterator();
                //遍历迭代器
                while (iterator.hasNext()) {
                    //获取遍历到的元素
                    FileItem item = iterator.next();
                    //判断item是否文件域参数
                    if (item.isFormField()) {
                        //获取普通表单字段的名称
                        String fieldName = item.getFieldName();
                        if ("categoryId".equals(fieldName)) {
                            //获取前端传来的普通表单字段数据，转换为整数后，为news对象的分类编号属性赋值
                            news.setCategoryId(Integer.parseInt(item.getString("UTF-8")));
                        } else if ("title".equals(fieldName)) {
                            news.setTitle(item.getString("UTF-8"));
                        } else if ("author".equals(fieldName)) {
                            news.setAuthor(item.getString("UTF-8"));
                        } else if ("summary".equals(fieldName)) {
                            news.setSummary(item.getString("UTF-8"));
                        } else if ("content".equals(fieldName)) {
                            news.setContent(item.getString("UTF-8"));
                        }
                    } else {
                        //处理文件上传;获取文件名称
                        String fileName = item.getName();
                        //关联上传后的文件
                        File uploadFile = new File(saveDirFile, fileName);
                        //文件上传
                        item.write(uploadFile);
                        news.setPicPath(fileName);
                    }
                }
            }
            //设置新闻的创建日期
            news.setCreateDate(new Date());
            //调用service的新闻增加方法
            NewsService newsService = new NewsServiceImpl();
            int count = newsService.addNews(news);
            if (count > 0) {
                response.sendRedirect("news.do?key=list");
            } else {
                response.getWriter().write("新闻增加失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void showOne(HttpServletRequest request, HttpServletResponse response) {
        News news = newsService.queryNewsById(Integer.parseInt(request.getParameter("id")));
        //把news对象存到page作用域里.键值对。news---news
        request.setAttribute("news", news);
        try {
            request.getRequestDispatcher("jsp/admin/newsDetailView.jsp").forward(request, response);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    private void list(HttpServletRequest request, HttpServletResponse response) {
        int curPagNo = 1;
        if (request.getParameter("curPageNo") != null
                && !request.getParameter("curPageNo").equals("")) {
            curPagNo = Integer.parseInt(request.getParameter("curPageNo"));
        }
        PageSupport<News> pageSupport = PageSupport.getInstance(curPagNo);
        newsService.queryPageNews(pageSupport);
        /*我们所需的一切分页信息都已经在pageSupport里了*/
        request.setAttribute("page", pageSupport);
        //以转发方式跳转到新闻列表页
        try {
            request.getRequestDispatcher("jsp/admin/newsDetailList.jsp").forward(request, response);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
